/** @type {HTMLCanvasElement}*/ 
const canvas = document.getElementById('canvas1')
const ctx = canvas.getContext('2d')
canvas.width = window.innerWidth
canvas.height = window.innerHeight

let mouse = {
    x:canvas.width/2,
    y:canvas.height/2
}
window.addEventListener('mousemove',function(event){
    mouse.x = event.clientX
    mouse.y = event.clientY
})
window.addEventListener('click',function(event){
    balls.forEach(ball => {
        if(Math.abs(ball.x - mouse.x) < ball.radius && Math.abs(ball.y - mouse.y) < ball.radius){
            ball.color = 'red'
        }
    })
})
window.addEventListener('resize',function(){
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
})
function Ball(x,y,dx,dy,radius,color){
    this.x = x
    this.y = y
    this.dx = dx
    this.dy = dy
    this.radius = radius
    this.minradius = radius
    this.color = color
    this.draw = function(){
        ctx.beginPath()
        ctx.fillStyle = this.color
        ctx.arc(this.x,this.y,this.radius,0,Math.PI*2,false) // 绘制圆线 ctx.stroke()
        ctx.fill() // 填充颜色
        ctx.closePath()
    }
    this.update = function(){
        if(this.x + this.radius > canvas.width || this.x - this.radius < 0){
            this.dx = -this.dx
        }
        if(this.y + this.radius > canvas.height || this.y - this.radius < 0){
            this.dy = -this.dy
        }
        this.x += this.dx
        this.y += this.dy

        if(mouse.x - this.x < 100 && mouse.x - this.x > -100 && mouse.y - this.y < 100 && mouse.y - this.y > -100){
            if(this.radius < 120){
                this.radius += 3
            }
         }
         else{
            if(this.radius > this.minradius){
                this.radius -= 1
            }
        }
    }
}

let ball = new Ball(100,100,2,2,30,'red')

let balls = []
for(let i = 0; i < 200; i++){
    let radius = Math.random()*40 + 10
    let x = Math.random()*(canvas.width - radius*2) + radius
    let y = Math.random()*(canvas.height - radius*2) + radius
    let dx = (Math.random() - 0.5) * 3
    let dy = (Math.random() - 0.5) * 3
    // let color = `hsl(${Math.random()*360}, 100%, 50%)`
    let color = `rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255})`
    balls.push(new Ball(x,y,dx,dy,radius,color))
}

function animate(){
    ctx.clearRect(0,0,canvas.width,canvas.height)
    requestAnimationFrame(animate)
    balls.forEach(ball => {
        ball.draw()
        ball.update()
    })
}
animate()
